﻿using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace Hsenl {
    [Serializable]
    public class DBCollection {
        [JsonProperty]
        private List<DBDocument> _documents = new();

        [JsonIgnore]
        public string FileName { get; internal set; } // 临时储存这次加载时的文件名

        [JsonIgnore]
        public string FilePath { get; internal set; } // 临时储存这次加载时的文件路径
        
        public DBDocument Insert<T>(string idxName, T idxValue) {
            var doc = this.Get(idxName, idxValue);
            if (doc != null)
                throw new Exception($"Document '{idxName}:{idxValue}' already exists");

            doc = new DBDocument();
            doc.InsertOne(idxName, idxValue);
            this._documents.Add(doc);
            return doc;
        }

        public DBDocument Insert() {
            if (this._documents.Count != 0)
                throw new Exception($"This collection is not single");

            var doc = new DBDocument();
            this._documents.Add(doc);
            return doc;
        }

        public DBDocument Get<T>(string idxName, T idxValue) {
            foreach (var document in this._documents) {
                var v = document.GetValue<T>(idxName);
                if (v.Equals(idxValue)) {
                    return document;
                }
            }

            return null;
        }

        public DBDocument Get() {
            if (this._documents.Count != 0)
                return this._documents[0];

            return null;
        }

        public void Save() {
            if (string.IsNullOrEmpty(this.FilePath))
                throw new FileNotFoundException("The collection's file path is empty");
            
            var bin = DatabaseManager.Instance.Serialize.Serialize(this);
            using var fs = new FileStream(this.FilePath, FileMode.OpenOrCreate, FileAccess.Write);
            fs.SetLength(0);
            fs.Write(bin);
        }
    }
}